<template>
    <div class="admin-layout">
        <aside class="sidebar">
            <header class="sidebar-header">
                <router-link :to="isShopkeeper ? '/admin/dashboard-shopkeeper' : '/admin/dashboard'">
                    {{ isShopkeeper ? '商家管理后台' : '宠物商店后台' }}
                </router-link>
            </header>
            <ul class="nav">
                <li class="nav-item">
                    <router-link :to="isShopkeeper ? '/admin/dashboard-shopkeeper' : '/admin/dashboard'" class="nav-link" active-class="active">
                        <svg viewBox="0 0 24 24"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8h5z"></path></svg>
                        <span>统计</span>
                    </router-link>
                </li>
                <li class="nav-item dropdown">
                    <div @click="toggleProductsMenu" class="nav-link" :class="{ active: $route.path.includes('/admin/products') }">
                        <svg viewBox="0 0 24 24"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6-4c1.66 0 3 1.34 3 3v2H9V6c0-1.66 1.34-3 3-3zm6 14H6V10h12v10z"></path></svg>
                        <span>商品管理</span>
                        <svg class="dropdown-icon" :class="{ 'rotated': productsMenuOpen }" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5H7z"></path></svg>
                    </div>
                    <ul v-show="productsMenuOpen" class="sub-menu">
                        <li class="sub-menu-item">
                            <router-link to="/admin/products" class="sub-menu-link" active-class="active">
                                <span>所有商品</span>
                            </router-link>
                        </li>
                        <li v-for="store in stores" :key="store.storeId" class="sub-menu-item">
                            <router-link :to="`/admin/products/${store.storeId}`" class="sub-menu-link" active-class="active">
                                <span>{{ store.name }}</span>
                            </router-link>
                        </li>
                        <li v-if="storesLoading" class="sub-menu-item">
                            <span class="sub-menu-link">加载中...</span>
                        </li>
                    </ul>
                </li>
                <li class="nav-item">
                    <router-link to="/admin/stores" class="nav-link" active-class="active">
                        <svg viewBox="0 0 24 24"><path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10z"></path></svg>
                        <span>商店管理</span>
                    </router-link>
                </li>
                <li class="nav-item dropdown">
                    <div @click="toggleVideosMenu" class="nav-link" :class="{ active: $route.path.includes('/admin/videos') }">
                        <svg viewBox="0 0 24 24"><path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path></svg>
                        <span>视频管理</span>
                        <svg class="dropdown-icon" :class="{ 'rotated': videosMenuOpen }" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5H7z"></path></svg>
                    </div>
                    <ul v-show="videosMenuOpen" class="sub-menu">
                        <li class="sub-menu-item">
                            <router-link to="/admin/videos" class="sub-menu-link" active-class="active">
                                <span>所有视频</span>
                            </router-link>
                        </li>
                        <li v-for="store in stores" :key="store.storeId" class="sub-menu-item">
                            <router-link :to="`/admin/videos/${store.storeId}`" class="sub-menu-link" active-class="active">
                                <span>{{ store.name }}</span>
                            </router-link>
                        </li>
                        <li v-if="storesLoading" class="sub-menu-item">
                            <span class="sub-menu-link">加载中...</span>
                        </li>
                    </ul>
                </li>
                <li class="nav-item" v-if="isAdmin">
                    <router-link to="/admin/members" class="nav-link" active-class="active">
                        <svg viewBox="0 0 24 24"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"></path></svg>
                        <span>会员管理</span>
                    </router-link>
                </li>
            </ul>
            <div class="sidebar-footer">
                <div class="user-info">
                    <img :src="currentUser.avatar || '/avatar/avatar.png'" alt="用户头像" class="user-avatar">
                    <div class="user-details">
                        <span class="user-name">{{ currentUser.username || '管理员' }}</span>
                        <span class="user-role">{{ userRole }}</span>
                    </div>
                </div>
                <button @click="logout" class="logout-btn">
                    <svg viewBox="0 0 24 24"><path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"></path></svg>
                    <span>退出登录</span>
                </button>
            </div>
        </aside>
        <main class="main-content">
            <router-view></router-view>
        </main>
    </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import { onMounted, ref, computed } from 'vue';
import { api } from '@/network/api';

interface Store {
    storeId: number;
    name: string;
}

// 定义用户信息接口
interface UserInfo {
    username?: string;
    avatar?: string;
    memberLevel?: string | number;
}

const router = useRouter();
const isAdmin = ref(true);
const isShopkeeper = ref(false);
const productsMenuOpen = ref(false);
const videosMenuOpen = ref(false);
const stores = ref<Store[]>([]);
const storesLoading = ref(true);
const currentUser = ref<UserInfo>({}); // 用于存储当前用户信息

const userRole = computed(() => {
    if (currentUser.value.memberLevel == '-2') {
        return '管理员';
    }
    if (currentUser.value.memberLevel == '-1') {
        return '商家';
    }
    return '未知身份';
});

const toggleProductsMenu = () => {
    const wasOpen = productsMenuOpen.value;
    // 关闭所有菜单
    videosMenuOpen.value = false;
    // 切换当前菜单
    productsMenuOpen.value = !wasOpen;
};

const toggleVideosMenu = () => {
    const wasOpen = videosMenuOpen.value;
    // 关闭所有菜单
    productsMenuOpen.value = false;
    // 切换当前菜单
    videosMenuOpen.value = !wasOpen;
};

const fetchStores = async () => {
    storesLoading.value = true;
    try {
        const response = await api.getStoreList(); // 获取所有商店
        
        // 处理StoresInfo数据结构
        if (response && response.data && Array.isArray(response.data)) {
            // 使用Map按storeId去重
            const storeMap = new Map();
            
            response.data.forEach((storeInfo: any) => {
                if (storeInfo && storeInfo.stores) {
                    const store = {
                        storeId: storeInfo.stores.storeId,
                        name: storeInfo.stores.name
                    };
                    
                    // 使用storeId作为唯一键，避免重复
                    if (!storeMap.has(store.storeId)) {
                        storeMap.set(store.storeId, store);
                    }
                }
            });
            
            // 将Map转换回数组
            stores.value = Array.from(storeMap.values());
        } else {
            stores.value = response.data || [];
        }
    } catch (error) {
        console.error('获取商店列表失败:', error);
    } finally {
        storesLoading.value = false;
    }
};

const checkMemberLevel = () => {
    try {
        console.log('检查用户级别...');
        const userInfoStr = localStorage.getItem('user_info');
        console.log('用户信息原始字符串:', userInfoStr);

        if (!userInfoStr) {
            console.log('未找到用户信息');
            router.push('/login');
            return;
        }

        const userInfo = JSON.parse(userInfoStr);
        console.log('解析后的用户信息:', userInfo);

        // 检查顶层属性以及data对象内的属性
        const memberLevel = userInfo.memberLevel || userInfo.data?.memberLevel;
        console.log('获取到的会员等级:', memberLevel);

        if (memberLevel === '-1') {
            console.log('用户是商家');
            isAdmin.value = false;
            isShopkeeper.value = true;

            // 如果当前在仪表盘页面，重定向到商家仪表盘
            if (router.currentRoute.value.path === '/admin/dashboard') {
                console.log('重定向商家到商家仪表盘');
                router.push('/admin/dashboard-shopkeeper');
            }
        } else if (memberLevel !== '-2') {
            console.log('用户是普通会员');
            isAdmin.value = false;
            isShopkeeper.value = false;
        } else {
            console.log('用户是管理员');
            isAdmin.value = true;
            isShopkeeper.value = false;
        }
    } catch (error) {
        console.error('解析用户信息时出错:', error);
        router.push('/login');
    }
};

const checkAndSetUserInfo = () => {
  const userInfoStr = localStorage.getItem('user_info');
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr);
      currentUser.value = userInfo; // 保存用户信息
      if (userInfo.memberLevel != '-2') {
        isAdmin.value = false;
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
      currentUser.value = {}; // 解析失败则清空
    }
  }
};

const logout = () => {
    localStorage.removeItem('user_info');
    router.push('/login');
};

onMounted(() => {
    checkAndSetUserInfo();
    checkMemberLevel();
    fetchStores();
});
</script>

<style scoped>
.admin-layout {
    display: flex;
    height: 100vh;
    background-color: #fbfbfb;
    overflow: hidden;
}
.sidebar {
    width: 15%;
    background-color: #3498db;
    color: #ffffff;
    display: flex;
    flex-direction: column;
    padding-top: 20px;
    flex-shrink: 0;
}
.sidebar-header {
    padding: 0 20px 20px 20px;
    font-size: 2em;
    font-weight: bold;
    text-align: center;
    border-bottom: 1px solid #3498db;
}
.sidebar-header a {
    color: #ecf0f1;
    text-decoration: none;
}
.nav {
    list-style: none;
    padding: 20px 0;
    margin: 0;
    flex-grow: 1;
}
.nav-item {
    padding: 0;
}
.nav-link {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    color: #ffffff;
    text-decoration: none;
    transition: background-color 0.3s, color 0.3s;
    font-size: 1.5em;
    cursor: pointer;
}
.nav-link:hover, .nav-link.active {
    background-color: #3b9ddf;
    color: #ffffff;
}
.nav-link svg {
    width: 20px;
    height: 20px;
    margin-right: 15px;
    fill: currentColor;
}
.main-content {
    flex-grow: 1;
    overflow-y: auto;
}

.sidebar-footer {
    padding: 20px;
    border-top: 1px solid #3b9ddf;
}

.user-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 15px;
    object-fit: cover;
    border: 2px solid #fff;
}

.user-details {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-size: 1.2em;
    font-weight: 500;
    line-height: 1.2;
}

.user-role {
    font-size: 0.9em;
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
    padding: 2px 8px;
    border-radius: 4px;
    font-weight: 400;
    align-self: flex-start;
    margin-top: 4px;
}

.logout-btn {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 15px 20px;
    background-color: transparent;
    border: none;
    color: #ffffff;
    text-align: left;
    font-size: 1.5em;
    cursor: pointer;
    transition: background-color 0.3s;
}
.logout-btn:hover {
    background-color: #3b9ddf;
}
.logout-btn svg {
    width: 20px;
    height: 20px;
    margin-right: 15px;
    fill: currentColor;
}

/* 下拉菜单样式 */
.dropdown-icon {
    width: 16px;
    height: 16px;
    margin-left: auto;
    transition: transform 0.3s;
}
.dropdown-icon.rotated {
    transform: rotate(180deg);
}
.sub-menu {
    list-style: none;
    padding: 0;
    margin: 0;
    background-color: #2980b9;
}
.sub-menu-item {
    padding: 0;
}
.sub-menu-link {
    display: flex;
    align-items: center;
    padding: 12px 20px 12px 40px;
    color: #ffffff;
    text-decoration: none;
    transition: background-color 0.3s;
    font-size: 1.2em;
}
.sub-menu-link:hover, .sub-menu-link.active {
    background-color: #2471a3;
}
</style> 